#include "PixelBuffer.h"

namespace egg{

    PixelBuffer::PixelBuffer(Type type):
    mDevicePixelFormat(PF_R8G8B8A8){
        mSize = 0;
        mWidth = 0;
        mHeight = 0;
        mType=type;
        glGenBuffers(1, &mID);
        GraphicDevice_CatchError;
    }

    PixelBuffer::~PixelBuffer(){
        glDeleteBuffers(1, &mID);
        GraphicDevice_CatchError;
    }

    void PixelBuffer::resize(uint32 size,BufferUsage usage){
        glBindBuffer(mType,mID);
        glBufferData(mType, size, 0, usage);
        glBindBuffer(mType,0);
        mUsage=usage;
        mSize=size;
        GraphicDevice_CatchError;
    }

    void PixelBuffer::fromScreen(uint32 w,uint32 h){
        glBindBuffer(mType,mID);
        glReadPixels(
            0, 0, mWidth, mHeight, 
            mDevicePixelFormat.mFormat, 
            mDevicePixelFormat.mType, 
            NULL);
        glBindBuffer(mType,0);
        GraphicDevice_CatchError;
    }

    void PixelBuffer::fromTexture2D(Texture2DPtr tex){
        glBindBuffer(mType,mID);
        glBindTexture(GL_TEXTURE_2D,tex->getID());
        glGetTexImage(GL_TEXTURE_2D,0,mDevicePixelFormat.mFormat,mDevicePixelFormat.mType,0);
        glBindTexture(GL_TEXTURE_2D,0);
        glBindBuffer(mType,0);
        GraphicDevice_CatchError;
    }

    void PixelBuffer::toTexture2D(Texture2DPtr tex){
        glBindBuffer(mType,mID);
        tex->writePixels(0);
        glBindBuffer(mType,0);
        GraphicDevice_CatchError;
    }

    void* PixelBuffer::_lock(BufferAcess acess){
        glBindBuffer(mType,mID);
        void* ret=glMapBuffer(mType, GL_WRITE_ONLY);
        GraphicDevice_CatchError;
        return ret;
    }

    void PixelBuffer::_unlock(){
        glUnmapBuffer(mType);
        glBindBuffer(mType,0);
        GraphicDevice_CatchError;
    }

}